﻿using SuperMap.Data;
using SuperMap.Realspace;
using System;
using System.Data;
using System.Drawing;
using System.Windows.Forms;

namespace Ycjw.PipeLine.Map.Basic.Results
{
    public class ResultWindowWithDataGridView: ResultWindow
    {
        public DataGridView m_DataGridView;
        Sunny.UI.UIGroupBox m_UIGroupBox;
        public ResultWindowWithDataGridView() : base()
        {
            m_DataGridView = new DataGridView()
            { 
                Dock = DockStyle.Fill ,
                ShowEditingIcon = false,
                AllowUserToAddRows = false,
                ReadOnly = true,
                MultiSelect =false
            };
            m_UIGroupBox = new Sunny.UI.UIGroupBox(){
                Dock  = DockStyle.Fill
            };
            this.Controls.Add(m_UIGroupBox);
            CreateExportExcelButton();
            m_UIGroupBox.Controls.Add(m_DataGridView);
            this.m_DataGridView.RowPostPaint += DataGridView_RowPostPaint;

            this.m_DataGridView.CellMouseDoubleClick += DataGridView_CellMouseDoubleClick;
            uiSymbolButtonExportToExcel.Click += UiSymbolButtonExportToExcel_Click;
        }

        private void UiSymbolButtonExportToExcel_Click(object sender, EventArgs e)
        {
            if (m_DataGridView == null) return;
            var errMsg = Commons.ExportDgvToExcel.ExportExcel(string.Empty, this.m_DataGridView, "雅黑", 14);
            if (!string.IsNullOrEmpty(errMsg))
            {
                if (errMsg == Commons.ExportDgvToExcel.CANCELRESULTSTRING) return;
                Sunny.UI.UINotifier.Show(errMsg, Sunny.UI.UINotifierType.ERROR, "错误", false, 1000);
            }
            else
            {
                Sunny.UI.UINotifier.Show("导出成功", Sunny.UI.UINotifierType.OK, "消息", false, 1000);
            }
        }

        protected void DataGridView_CellMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            var dataGridView = (sender as DataGridView);
            var selectRows = dataGridView.SelectedRows;
            if (selectRows == null || selectRows.Count == 0)
            {
                return;
            }
            var selectRow = selectRows[0];
            var smid = GetSMID(selectRow);
            if (smid == -1) return;

            Layer3DDataset lyr = GetLayer3DInScene((dataGridView.DataSource as DataTable).TableName);
            if (lyr == null) return;

            lyr.Selection.Add(smid);

            var geometry = GetGeometryByID(smid, lyr);
            if (geometry == null) return;

            SceneControl.Scene.LookAt = new LookAt(geometry.InnerPoint.X, geometry.InnerPoint.Y, 600);
        }

        protected Geometry GetGeometryByID(int smid, Layer3DDataset layer3DDataset)
        {
            DatasetVector dsv = layer3DDataset.Dataset as DatasetVector;
            var fs = dsv.GetAllFeatures();
            if (fs.ContainsKey(smid))
            {
                return fs[smid].GetGeometry();
            }
            return null;
        }
        protected string GetLayerCapation(string layerName)
        {
            var layer3DDataset = GetLayer3DInScene(layerName);
            if (layer3DDataset == null) return layerName;
            return layer3DDataset.Caption;
        }
        protected Layer3DDataset GetLayer3DInScene(string layerName)
        {
            var sc = this.SceneControl;
            if (sc == null) return null;
            foreach(Layer3D lyr in sc.Scene.Layers)
            {
                if (lyr.Name != layerName) continue;
                if(!(lyr is Layer3DDataset)) continue;

                var layer3DDataset = lyr as Layer3DDataset;
                return layer3DDataset;
            }
            return null;
        }
        protected int GetSMID(DataGridViewRow dr)
        {
            var smidName = "SMID";
            var index = -1;
            foreach (DataGridViewColumn c in dr.DataGridView.Columns)
            {
                if(c.Name.ToUpper() == smidName)
                {
                    index = dr.DataGridView.Columns.IndexOf(c);
                    break;
                }
            }
            if (index == -1) return -1;
            var val = dr.Cells[index].Value;
            if (val == null) return -1;
            return int.Parse(val.ToString());
        }

        protected virtual void DataGridView_RowPostPaint(object sender, DataGridViewRowPostPaintEventArgs e)
        {
            var dgv = sender as DataGridView;
            Rectangle rect = new Rectangle(e.RowBounds.Location.X, e.RowBounds.Location.Y,
                   dgv.RowHeadersWidth - 4, e.RowBounds.Height);
            TextRenderer.DrawText(e.Graphics, (e.RowIndex + 1).ToString(),
                dgv.RowHeadersDefaultCellStyle.Font, rect,
                dgv.RowHeadersDefaultCellStyle.ForeColor,
                TextFormatFlags.VerticalCenter | TextFormatFlags.Right);
        }

        protected void SetDataGridViewStyle(DataGridView dgv)
        {
            dgv.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.DisplayedCells;
            dgv.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.AutoSize;
            foreach (DataGridViewColumn column in dgv.Columns)
            {
                if (column.Name.ToUpper().StartsWith("SM") && column.Name.ToUpper() != "SMID")
                {
                    column.Visible = false;
                }
            }
        }
        public override void ShowData(object data)
        {
            if (data == null)
            {
                m_UIGroupBox.Text = "无结果";
                DataTable dt = new DataTable();
                dt.Columns.Add("执行结果");
                var dr = dt.NewRow();
                dr[0] = "查询无结果";
                dt.Rows.Add(dr);
            }
            else if (data is DataTable)
            {
                var dt = data as DataTable;
                m_DataGridView.DataSource = dt;
                m_UIGroupBox.Text = GetLayerCapation(dt.TableName);
                SetDataGridViewStyle(m_DataGridView);
            }
            else
                throw new ArgumentException("需要的参数为DataTable");
        }
    }
}
